package com.sptpc.stu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.sptpc.stu.common.response.JSONResponse;
import com.sptpc.stu.controller.request.AddNewUserRequest;
import com.sptpc.stu.controller.request.UserBasicInfoRequest;
import com.sptpc.stu.controller.request.UserLoginInfoRequest;
import com.sptpc.stu.model.my.User;
import com.sptpc.stu.repository.my.UserRepository;
import com.sptpc.stu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Optional;


@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public JSONResponse getAllUser() {
        List<User> users  = userRepository.findAll();
        return JSONResponse.ofSuccess(users);
    }

    @Override
    public JSONResponse updateUserBasicInfo( UserBasicInfoRequest changeUserBasicInfo) {
        User user = userRepository.findByUid(changeUserBasicInfo.getUid()).get();


        BeanUtil.copyProperties(changeUserBasicInfo,user);

        userRepository.saveAndFlush(user);

        return JSONResponse.ofSuccess("修改用户信息成功");
    }

    @Override
    public JSONResponse updateUserLoginInfo(UserLoginInfoRequest changeUserLoginInfo) {

        User user = userRepository.findByUid(changeUserLoginInfo.getUid()).get();

        if (changeUserLoginInfo.getAccount()==null)
        {
            changeUserLoginInfo.setAccount(user.getAccountPhone());
        }
        if (changeUserLoginInfo.getEmail()==null)
        {
            changeUserLoginInfo.setEmail(user.getEmail());
        }
        if (user.getPassword().equals(DigestUtil.md5Hex(changeUserLoginInfo.getPassword())))
        {
            return JSONResponse.ofFail("新旧密码一致");
        }

        BeanUtil.copyProperties(changeUserLoginInfo,user);

        user.setPassword(DigestUtil.md5Hex(user.getPassword()));

        userRepository.saveAndFlush(user);

        return JSONResponse.ofSuccess("密码修改成功");
    }

    @Override
    public JSONResponse getRandomUserinfo() {
        return JSONResponse.ofSuccess(userRepository.RandomfindUser());
    }

    @Override
    public JSONResponse deleteUser(Long uid) {
        User userExample = User.builder()
                .uid(uid).build();
        Example<User> example = Example.of(userExample);
        Optional<User> optionalUser = userRepository.findOne(example);
        if (optionalUser.isPresent()) {
            userRepository.deleteById(optionalUser.get().getUid());
            return JSONResponse.ofSuccess();
        } else {
            return JSONResponse.ofFail("输入的学号有误，请查询后再尝试");
        }
    }
}
